<!--
 * @Description: 
 * @Autor: Zhu_liangyu
 * @Date: 2020-05-09 10:52:56
--> 
<template>
  <div>
    <a-upload
      name="avatar"
      listType="picture-card"
      class="avatar-uploader"
      :data="uploadData"
      :headers="myHeader"
      :showUploadList="false"
      :action="uploadImgApi"
      :beforeUpload="beforeUpload"
      @change="handleChange"
    >
      <img width="100%" v-if="avatar" :src="imgUrl" alt="avatar" />
      <div v-else>
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">上传头像</div>
      </div>
    </a-upload>
    <span>只能上传jpg文件,且大小不能超过2MB</span>
  </div>
</template>
<script>
import { judgeUploadImage } from "@/utils/validate";
import { uploadImgApi, viewImgApi } from "@/api/common";
import { ACCESS_TOKEN } from "@/config/storageKey";
export default {
  props: {
    avatar: {
      type: String
    }
  },
  data() {
    return {
      uploadImgApi,
      loading: false,
      myHeader: {},
      uploadData: {
        itemType: "avatar"
      }
    };
  },
  created() {
    this.myHeader[ACCESS_TOKEN] = this.$store.getters.token;
  },
  methods: {
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        const { file, fileList } = info;
        const { response } = file;
        this.loading = false;
        this.$emit("uploadAvatarSuccess", response, file, fileList);
      }
    },
    beforeUpload(file) {
      return judgeUploadImage(file);
    }
  },
  computed: {
    imgUrl() {
      return viewImgApi + this.avatar;
    }
  }
};
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
